#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <erpc_server_setup.h>
#include "c_matrix_server.h"

#define USE_DEMO_MATRIX
#define USE_TCP_TRANSPORT

#ifdef USE_DEMO_MATRIX
void matrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result)
{
    int i, j, k;
printf("===== Matrix #1 =====\n");
    for(int i = 0; i < 5; i++){
        for(int j = 0; j < 5; j++){
            printf("%08d  ", matrix1[i][j]);
        }
        printf(";\n");
    }
printf("===== Matrix #2 =====\n");
    for(int i = 0; i < 5; i++){
        for(int j = 0; j < 5; j++){
            printf("%08d  ", matrix2[i][j]);
        }
        printf(";\n");
    }
    memset(result, 0, sizeof(Matrix));
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            for (k = 0; k < 5; k++) {
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }
printf("===== Result Matrix =====\n");
    for(int i = 0; i < 5; i++){
        for(int j = 0; j < 5; j++){
            printf("%08d  ", result[i][j]);
        }
        printf(";\n");
    }
}
#endif

int main(int argc, char *argv[])
{
#ifdef USE_TCP_TRANSPORT
    const char *device = "127.0.0.1";

    if (argc == 2) {
        device = argv[1];
    }
    erpc_transport_t transport = erpc_transport_tcp_init(device, 5555, true);
#else
    const char *device = "COM10";

    if (argc == 2) {
        device = argv[1];
    }
    erpc_transport_t transport = erpc_transport_serial_init(device, 115200);
#endif
    if (transport == NULL) {
        printf("erpc transport init error\n");
        return 0;
    }
    erpc_mbf_t message_buffer_factory = erpc_mbf_dynamic_init();
    
    erpc_server_t server = erpc_server_init(transport, message_buffer_factory);
    if (server == NULL) {
        printf("erpc_server_init error\n");
        return 0;
    }
#ifdef USE_DEMO_MATRIX
    erpc_service_t service = create_MatrixServer_service();
    if (service == NULL) {
        printf("create_MatrixServer_service error\n");
        return 0;
    }
    erpc_add_service_to_server(server, service);

    while(1){
        erpc_server_run(server);
    }

    destroy_MatrixServer_service(service);
#else
#endif

#ifdef USE_TCP_TRANSPORT
    erpc_transport_tcp_close(transport);
#endif

    return 0;
}

